package com.crm.business.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.crm.business.admin.service.AdminService;
import com.crm.business.crm.mapper.CrmCustomerPoolMapper;
import com.crm.business.crm.service.*;
import com.crm.common.crm.common.ElasticUtil;
import com.crm.common.crm.constant.CrmActivityEnum;
import com.crm.common.crm.constant.CrmCodeEnum;
import com.crm.common.crm.constant.CrmEnum;
import com.crm.common.crm.entity.BO.CrmCustomerPoolBO;
import com.crm.common.crm.entity.BO.CrmSearchBO;
import com.crm.common.crm.entity.PO.*;
import com.crm.common.ka.core.common.cache.CrmCacheKey;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.common.ka.core.entity.UserInfo;
import com.crm.common.ka.core.exception.CrmException;
import com.crm.common.ka.core.feign.crm.entity.ExamineField;
import com.crm.common.ka.core.feign.crm.entity.SimpleCrmEntity;
import com.crm.common.ka.core.redis.Redis;
import com.crm.business.servlet.ApplicationContextHolder;
import com.crm.common.ka.core.utils.TagUtil;
import com.crm.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service("crmCallService")
public class CrmCallServiceImpl implements CrmService {

    @Autowired
    ElasticsearchRestTemplate restTemplate;
    @Autowired
    private ICrmCustomerService crmCustomerService;
    @Autowired
    private ICrmContactsService crmContactsService;
    @Autowired
    private ICrmBusinessService crmBusinessService;
    @Autowired
    private ICrmContractService crmContractService;
    @Autowired
    private ICrmProductService crmProductService;
    @Autowired
    private ICrmActivityService crmActivityService;
    @Autowired
    Redis redis;
    @Autowired
    private ICrmCustomerPoolService crmCustomerPoolService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private ICrmCustomerPoolRuleService crmCustomerPoolRuleService;
    @Autowired
    private CrmCustomerPoolMapper crmCustomerPoolMapper;
    @Autowired
    private ICrmCustomerPoolRelationService crmCustomerPoolRelationService;
    @Autowired
    private ICrmOwnerRecordService crmOwnerRecordService;
    @Resource
    private CrmPageService customerPoolService;
    @Autowired
    private ICrmFieldService crmFieldService;
    @Autowired
    private ICrmPutinStatisticsService crmPutinStatisticsService;
    @Autowired
    private CrmLargeScreenSettingService crmLargeScreenSettingService;
    @Autowired
    private ICrmDealStatusService crmDealStatusService;
    @Autowired
    private ICrmTimeTableService crmTimeTableService;



    /**
     * 查询客户信息
     *
     * @param ids ids
     * @return entity
     */
    public List<SimpleCrmEntity> queryCustomerInfo(Collection ids){
        List<Integer> list = new ArrayList<>(ids);
        List<SimpleCrmEntity> crmEntities = crmCustomerService.querySimpleEntity(list);
        return crmEntities;
    }


    /**
     * 查询客户信息(like)
     *
     * @param name 名字
     * @return entity
     */
    public List<SimpleCrmEntity> queryByNameCustomerInfo(String name){
        List<SimpleCrmEntity> crmEntities = crmCustomerService.queryByNameCustomerInfo(name);
        return crmEntities;
    }


    /**
     * 查询客户信息(eq)
     *
     * @param name 名字
     * @return entity
     */
    public List<SimpleCrmEntity> queryNameCustomerInfo(String name){
        List<SimpleCrmEntity> crmEntities = crmCustomerService.queryNameCustomerInfo(name);
        return crmEntities;
    }

    /**
     * 查询联系人信息
     *
     * @param ids ids
     * @return entity
     */
    public List<SimpleCrmEntity> queryContactsInfo(Collection ids){
        List<Integer> list = new ArrayList<>(ids);
        List<SimpleCrmEntity> crmEntities = crmContactsService.querySimpleEntity(list);
        return crmEntities;
    }

    /**
     * 查询商机信息
     *
     * @param ids ids
     * @return entity
     */
    public List<SimpleCrmEntity> queryBusinessInfo(Collection ids){
        List<Integer> list = new ArrayList<>(ids);
        List<SimpleCrmEntity> crmEntities = crmBusinessService.querySimpleEntity(list);
        return crmEntities;
    }

    /**
     * 查询合同信息
     *
     * @param ids ids
     * @return entity
     */
    public List<SimpleCrmEntity> queryContractInfo(Collection ids){
        List<Integer> list = new ArrayList<>(ids);
        List<SimpleCrmEntity> crmEntities = crmContractService.querySimpleEntity(list);
        return crmEntities;
    }

    public List<SimpleCrmEntity> queryProductInfo(){
        List<SimpleCrmEntity> crmEntities = crmProductService.querySimpleEntity();
        return crmEntities;
    }

    /**
     * 添加活动记录
     *
     * @param type
     * @param activityType   活动类型
     * @param activityTypeId 类型ID
     * @return
     */
    public void addActivity(Integer type, Integer activityType, Integer activityTypeId){
        crmActivityService.addActivity(type, CrmActivityEnum.parse(activityType), activityTypeId);
    }

    public void batchUpdateEsData(String id, String name){
        ElasticUtil.batchUpdateEsData(restTemplate.getClient(), "user", id, name);
    }

    @Transactional(rollbackFor = Exception.class)
    public void putInInternational(){
        try {
            UserInfo userInfo = redis.get(CrmCacheKey.CRM_CUSTOMER_JOB_CACHE_KEY);
            List<CrmCustomerPool> poolList = crmCustomerPoolService.lambdaQuery()
                    .eq(CrmCustomerPool::getStatus, 1).eq(CrmCustomerPool::getPutInRule, 1).list();
            poolList.forEach(pool -> {
                List<Long> userIdsList = new ArrayList<>();
                if (StrUtil.isNotEmpty(pool.getMemberDeptId())) {
                    List<Integer> ids = new ArrayList<>(TagUtil.toSet(pool.getMemberDeptId()));
                    userIdsList = adminService.queryUserByDeptIds(ids);
                }
                if (StrUtil.isNotEmpty(pool.getMemberUserId())) {
                    userIdsList.addAll(TagUtil.toLongSet(pool.getMemberUserId()));
                }
                Set<Integer> customerIdSet = new HashSet<>();
                List<CrmCustomerPoolRule> ruleList = crmCustomerPoolRuleService.lambdaQuery().eq(CrmCustomerPoolRule::getPoolId,pool.getPoolId()).list();
                for (CrmCustomerPoolRule rule : ruleList) {
                    Map<String, Object> record = BeanUtil.beanToMap(rule);
                    if (CollectionUtil.isNotEmpty(userIdsList)) {
                        record.put("ids", userIdsList);
                    }
                    //公海名称查询  根据客户所属公海 判断进入那个公海
                    record.put("poolName",pool.getPoolName());
                    if (rule.getType().equals(1)) {
                        Set<Integer> ids = crmCustomerPoolMapper.putInPoolByRecord(record);
                        customerIdSet.addAll(ids);
                    } else if (rule.getType().equals(2)) {
                        Set<Integer> ids = crmCustomerPoolMapper.putInPoolByBusiness(record);
                        customerIdSet.addAll(ids);
                    } else if (rule.getType().equals(3)) {
                        Set<Integer> ids = crmCustomerPoolMapper.putInPoolByDealStatus(record);
                        customerIdSet.addAll(ids);
                    }
                }
                List<Integer> customerIdList = crmCustomerPoolRelationService.lambdaQuery().select(CrmCustomerPoolRelation::getCustomerId)
                        .eq(CrmCustomerPoolRelation::getPoolId,pool.getPoolId()).list()
                        .stream().map(CrmCustomerPoolRelation::getCustomerId).collect(Collectors.toList());
                customerIdSet.removeAll(customerIdList);
                customerIdSet.forEach(customerId -> {
                    CrmCustomer crmCustomer = crmCustomerService.getById(customerId);
                    if (ObjectUtil.isNotEmpty(crmCustomer.getOwnerUserId())) {
                        CrmOwnerRecord crmOwnerRecord = new CrmOwnerRecord();
                        crmOwnerRecord.setTypeId(customerId);
                        crmOwnerRecord.setType(CrmEnum.CUSTOMER_POOL.getType());
                        crmOwnerRecord.setPreOwnerUserId(crmCustomer.getOwnerUserId());
                        crmOwnerRecordService.save(crmOwnerRecord);
                        crmCustomerService.lambdaUpdate()
                                .set(CrmCustomer::getPreOwnerUserId,crmOwnerRecord.getPreOwnerUserId())
                                .set(CrmCustomer::getOwnerUserId,null)
                                //助教协作人设置为null
                                .set(CrmCustomer::getAssistantUserId,null)
                                .set(CrmCustomer::getPoolTime,new Date())
                                .set(CrmCustomer::getIsReceive, null)
                                .set(CrmCustomer::getRoUserId, ",")
                                .set(CrmCustomer::getRwUserId, ",")
                                .eq(CrmCustomer::getCustomerId,customerId).update();
                    }
                    CrmCustomerPoolRelation customerPoolRelation = new CrmCustomerPoolRelation();
                    customerPoolRelation.setCustomerId(customerId);
                    customerPoolRelation.setPoolId(pool.getPoolId());
                    crmCustomerPoolRelationService.save(customerPoolRelation);
                });
                if (CollUtil.isNotEmpty(customerIdSet)){
                    SpringUtils.getBean(ICrmContactsService.class).lambdaUpdate()
                            .set(CrmContacts::getOwnerUserId,null)
                            .in(CrmContacts::getCustomerId,customerIdSet).update();
                    CrmCustomerPoolBO crmCustomerPoolBO = new CrmCustomerPoolBO();
                    List<Integer> ids = new ArrayList<>(customerIdSet);
                    crmCustomerPoolBO.setIds(ids);
                    crmCustomerPoolBO.setPoolId(pool.getPoolId());
                    customerPoolService.putInPool(crmCustomerPoolBO);
                }
            });
            return ;
        }catch (Exception e){
            e.printStackTrace();
            throw new CrmException(500,e.getMessage());
        }
    }

    public List<CrmCustomerPool> queryPoolNameListByAuth() {
        List<CrmCustomerPool> crmCustomerPools = crmCustomerPoolService.queryPoolNameListByAuth();
        return crmCustomerPools;
    }

    public List<ExamineField> queryExamineField(Integer label){
        List<ExamineField> fieldList = crmFieldService.queryExamineField(label);
        return fieldList;
    }

    public BasePage<Map<String, Object>> queryCustomerPageList(CrmSearchBO search){
        search.setPageType(1);
        BasePage<Map<String, Object>> mapBasePage = crmCustomerService.queryPageList(search);
        return mapBasePage;
    }

    public void roiSatistics(){
        crmPutinStatisticsService.roiSatistics();
    }

    public void updateLargeScreenSettingDataStatus(String checkStatus, String batchId){
        crmLargeScreenSettingService.updateLargeScreenSettingDataStatus(checkStatus,batchId);
    }


    public void updateCrmDealStatus(){
        boolean update = crmDealStatusService.update();
        if (update){
            return ;
        }
        throw new CrmException(CrmCodeEnum.CRM_UPDATE);
    }

    public CrmTimeTable queryTimeTableDataById(Integer id){
        return crmTimeTableService.queryById(id);
    }
}
